package com.hhwy.framework.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ClassUtils;

/**
 * Description
 * 
 * @author Lihuiming
 * @version 1.0
 */
public class IoTools {
	/***/
	private static String ABS_PATH = "";
	private static String CLASSES_PATH;
	private static ResourcePatternResolver resourcePatternResolver ;

	static {
		if (ABS_PATH.length() == 0) {
			CLASSES_PATH = Thread.currentThread().getContextClassLoader()
					.getResource("").getFile();
			ABS_PATH = CLASSES_PATH.replaceAll("^file:", "").replaceAll("WEB-INF/.*", "");//replace("WEB-INF/classes/", "");

			init();
			
			System.setProperty("runtime.path", ABS_PATH);
		}
	}
	/**
	 * 
	 * scan(在classpath下扫描资源文件)<br/>
	 * 
	 * @param packageName
	 * @return
	 * @throws IOException
	 *             Resource[]
	 * @exception
	 * @since 1.0.0
	 */
	public static Resource[] scan(String packageName, String resourcePattern, ClassLoader classLoader)
			throws IOException {
		resourcePatternResolver = new PathMatchingResourcePatternResolver(classLoader);
		String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
				+ ClassUtils.convertClassNameToResourcePath(packageName)
				+ resourcePattern;
		
		Resource[] resources =  filterXML(resourcePatternResolver.getResources(pattern));
		return resources;
	}
	/**
	 * 
	 * scan(在classpath下扫描资源文件)<br/>
	 * 
	 * @param packageName
	 * @return
	 * @throws IOException
	 *             Resource[]
	 * @exception
	 * @since 1.0.0
	 */
	public static Resource[] scan(String packageName, String resourcePattern)
			throws IOException {
		resourcePatternResolver = new PathMatchingResourcePatternResolver();
		String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
				+ ClassUtils.convertClassNameToResourcePath(packageName)
				+ resourcePattern;
		
		Resource[] resources =  filterXML(resourcePatternResolver.getResources(pattern));
		return resources;
	}
	/**
	 * filetXML(过滤重复资源，重复资源只加载目录中的)<br/>
	 * @param contextResourcesIn
	 * @return 
	 * Resource []
	 * @throws IOException 
	 * @exception 
	 * @since  1.0.0
	*/
	private static Resource[] filterXML(Resource[] contextResourcesIn) throws IOException {
		Map<String,Resource> contextMap = new HashMap<String, Resource>();
		for (int i = 0; i < contextResourcesIn.length; i++) {
			Resource resource = contextResourcesIn[i];
			if(resource.getURL().toString().startsWith("jar:")){
				String xmlName = resource.getURL().toString().split("jar!")[1];
				if(!contextMap.containsKey(xmlName))
					contextMap.put(xmlName, resource);
				
			}
			if(resource.getURL().toString().startsWith("file:")){
				String xmlName = resource.getURL().toString().split("classes")[1];
				contextMap.put(xmlName, resource);
			}
			
		}
		
		return contextMap.values().toArray(new Resource[contextMap.size()]);
	}
	private static void init() {

		String OS = System.getenv("OS");
		if (OS != null){
			if (OS.toUpperCase().indexOf("WINDOWS") > -1 && CLASSES_PATH.startsWith("/"))
				CLASSES_PATH = CLASSES_PATH.substring(1, CLASSES_PATH.length());
			
			if (OS.toUpperCase().indexOf("WINDOWS") > -1 && ABS_PATH.startsWith("/"))
				ABS_PATH = ABS_PATH.substring(1, ABS_PATH.length());
		}

		CLASSES_PATH = CLASSES_PATH.replace("\\\\", "/").replace("\\", "/");
		ABS_PATH = ABS_PATH.replace("\\\\", "/").replace("\\", "/");

	}

	public static String getClassesPath() {
		
		return CLASSES_PATH;
	}
	//只有在特殊情况下,当路径不正确时，用作矫正路径使用，一般情况下不要调用
	protected static void setClassesPath(String classPath) {
		
		CLASSES_PATH = classPath;
	}

	public static String getABSPATH() {

		return ABS_PATH;
	}
	//只有在特殊情况下,当路径不正确时，用作矫正路径使用，一般情况下不要调用
	protected static void setABSPATH(String absPath) {
		
		ABS_PATH = absPath;
	}

	/**
	 * 
	 * @param aBS_PATH2
	 * @return
	 */
	public static String upDir(String aBS_PATH2) {

		StringBuffer path = new StringBuffer();

		char[] cArray = aBS_PATH2.toCharArray();

		int count = 0;
		for (int i = cArray.length - 1; i > 0; i--) {

			//
			if (cArray[i] == 92 || cArray[i] == 47) {
				//
				if (count == 1) {
					for (int j = 0; j < i + 1; j++) {
						path.append(cArray[j]);
					}

				}
				count++;
			}

		}

		return path.toString();
	}

	/**
	 *
	 * @param tempDir2
	 */
	public static void deleteDir(File dir) {

		if (dir == null || !dir.exists() || !dir.isDirectory()) {
			if (dir.isFile())
				dir.delete();
			return;
		}
		for (File file : dir.listFiles()) {
			if (file.isFile())
				file.delete();
			else if (file.isDirectory())
				deleteDir(file);
		}
		dir.delete();
	}

}